﻿using System.Reflection;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

namespace SharePoint.Orm.Helpers {
    public static class ListViewWebPartHelper {
        public static void SetToolbarType(
            this ListViewWebPart lvwp,
            SPLimitedWebPartManager limitedWebPartManager,
            ListViewWebPartToolbarType type) {
#pragma warning disable 618
            string storageKey = lvwp.StorageKey.ToString("B").ToUpper();
            string listId = lvwp.ListName;
            string viewId = lvwp.ViewGuid;
            uint toolbarType = (uint)type;

            // get the SPWebPartManager from SPLimitedWebPartManager
            PropertyInfo webPartManagerProp = typeof(SPLimitedWebPartManager).GetProperty(
                "WebPartManager",
                BindingFlags.NonPublic | BindingFlags.Instance);
            SPWebPartManager webPartManager = (SPWebPartManager)webPartManagerProp.GetValue(limitedWebPartManager, null);

            // get the SPWebPartConnection from SPWebPartManager
            PropertyInfo spWebPartsProp = typeof(SPWebPartManager).GetProperty(
                "SPWebParts",
                BindingFlags.NonPublic | BindingFlags.Instance);
            SPWebPartCollection webParts = (SPWebPartCollection)spWebPartsProp.GetValue(webPartManager, null);

            // Call the ApplyViewToListWebPart method on the SPWebPartConnection
            // internal void ApplyViewToListWebPart(
            //    string storageKey,
            //    string listID,
            //    string viewID,
            //    uint toolbarType,
            //    out uint flags)
            MethodInfo applyViewToListWebPart = typeof(SPWebPartCollection).GetMethod(
                "ApplyViewToListWebPart",
                BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                new[]{
                    typeof(string),
                    typeof(string),
                    typeof(string),
                    typeof(uint),
                    typeof(uint).MakeByRefType()
                },
                null);
            object[] parameters = new object[5];
            parameters[0] = storageKey;
            parameters[1] = listId;
            parameters[2] = viewId;
            parameters[3] = toolbarType;
            applyViewToListWebPart.Invoke(webParts, parameters);
#pragma warning restore 618
        }
    }

    public enum ListViewWebPartToolbarType {
        Full = 0,
        Summary = 1,
        NoToolbar = 2
    }
}
